<?php

namespace frontend\controllers;

use Yii;
use common\models\meeting\Meeting;
use common\models\meeting\MeetingSearch;
use common\models\meeting\MeetingSign;
use common\models\meeting\Meetingenroll;
use common\models\AdminLog\AdminLog;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\Pagination;
use yii\base\Object;
use common\models\category\Category;
use yii\web\UploadedFile;
use zhongkefu\zhongkefu;
use zhongkefu\helpers\Utils;
use kartik\file\FileInput;//图片上传
use dosamigos\qrcode\QrCode;
use zhongkefu\helpers\SwfiEmail;
/**
 * ArticlesController implements the CRUD actions for Articles model.
 */
class MeetingenrollController extends Controller
{
    public $layout = 'enroll';
    /**
     * 报名
     * $id 会议id
     */
    public function actionCreate($id)
    {
    	// 当前位置信息
    	$tid = 4;
    	$parentinfo = Category::find()->where(['status'=> 1, 'id'=> $tid])->asArray()->one();

    	// 左侧导航栏
    	$childcat = Category::find()->where(['status'=> 1, 'parent_id'=> $tid])->asArray()->all();
    	$currentid = 19;
    	$currentinfo = Category::find()->where(['status'=> 1, 'id'=> $currentid])->asArray()->one();
    	// 导航状态
    	$view = Yii::$app->view;
    	$view->params['tid'] = $tid;
    	// 添加报名
		$res = Meeting::find()->where(['id' => $id])->one();
		$model = new Meetingenroll();
 		if($res->enroll == 1){
			if(Yii::$app->user->id){
				//会员id
				$member_id = Yii::$app->user->id;
				$ress = Meetingenroll::find()->where(['meeting_id' => $id, 'member_id' => $member_id])->asArray()->one();
                     //var_dump($ress);die();
				if(empty($ress)){

                //上传图片插件
                    if ($model->load(Yii::$app->request->post()) ) {
                        $model->label_img = UploadedFile::getInstance($model, 'label_img');
                        if($model->label_img){
                            $siteRoot = Yii::$app->params['meetingimg'];
                            //var_dump($siteRoot);die();
                            $json = Utils::uploadfile($_FILES['Meetingenroll']['tmp_name']['label_img'],$_FILES['Meetingenroll']['name']['label_img'],$siteRoot);    
                            $model->label_img = $json;
                            //var_dump($model->label_img);die();
                        }
						$model->meeting_id = $id;
						$model->created_at = time();
						$model->member_id = Yii::$app->user->id;
						if($model->save()){
                            //报名成功生成凭证码
                            $pingzheng = rand(10000,time());
                            $model->code = $pingzheng;
                            $model->save();
                            
				            header("Content-type: text/html; charset=utf-8");
				            echo "<script>alert('报名成功');history.go(-1);history.go(-1);</script>";
				            exit;
						}
    				}else{
    						return $this->render('create',[
    							'model' => $model,
    							'parentinfo' => $parentinfo,
    							'currentinfo' => $currentinfo,
    							'childcat' => $childcat,
    						]);
					}
				} else {
		            header("Content-type: text/html; charset=utf-8");
		            echo "<script>alert('您已经报名，请勿重复报名');history.go(-1);</script>";
		            exit;
				}

			}else{
				return $this->redirect(['/auth/login']);
			}
        } else {
            return $this->render('create', [
                'model' => $model,
                'parentinfo' => $parentinfo,
				'currentinfo' => $currentinfo,
				'childcat' => $childcat,
            ]);
        }
    }
    
	//报名培训内页
    public function actionMettingview($id){
        $message = Meeting::find()->where(['id' => $id])->asArray()->one();

        $articles = Meetingenroll::find()->where(['member_id'=>\Yii::$app->user->identity->getId()])->asArray()->all();
        
        foreach($articles as $k=>$t){
            if($t['meeting_id'] == $id){
                $last = $k - 1;
                $next = $k + 1;
          } 

      }

        if(isset($articles[$last])) {
            $lastone['meeting_id'] = $articles[$last]['meeting_id'];
            $Meetings = Meeting::find()->where(['id' => $lastone['meeting_id']])->asArray()->one();
            $lastone['id'] = $Meetings['id'];
            $lastone['name'] = $Meetings['title'];
        } else {
            $lastone['id'] = $id;
            $lastone['name'] = '没有了';
        }

        if(isset($articles[$next])) {
            $nextone['meeting_id'] = $articles[$next]['meeting_id'];
            $Meetings = Meeting::find()->where(['id' => $nextone['meeting_id']])->asArray()->one();
            $nextone['id'] = $Meetings['id'];
            $nextone['name'] = $Meetings['title'];
        } else {
            $nextone['id'] = $id;
            $nextone['name'] = '没有了';
        }
         return $this->render('view',[
            'message'=>$message,
            'lastone' => $lastone,
            'nextone' => $nextone,
        ]);
    }

 	public function actionView($id)
    {
		$model = $this->findModel($id);
		Adminlog::addlog(yii::$app->user->id, "查看在线留言 ".$model->title);
        return $this->render('view', [
            'model' => $model,
        ]);
    }

    /**
     * Lists all Articles models.
     * @return mixed
     */
    public function actionList()
    {
		$id = Yii::$app->user->id;
        $data = Meeting::find()->joinWith('meetingenroll')->where(['meetingenroll.member_id'=>$id]);
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => '4']);  
        $model = $data->offset($pages->offset)->limit($pages->limit)->asArray()->all(); //分页
		return $this->render('list',[
			'model' => $model,
			'page' => $pages,  
		]);
    }
	
/* 	public function actionList(){

		$cid = Yii::$app->request->get()["cid"];
		$artice_model = Articles::find()->where(['category_id' => $cid]);
		$pages = new Pagination(['totalCount'=>$artice_model->count(), 'pageSize'=>1]);	//分页
		//动态读取内容
		$datas = $artice_model->offset($pages->offset)
		->limit($pages->limit)
		->orderby('id DESC')
		->all();
		return $this->render('list',['list' => $datas,'pages' => $pages]);
	}
 */    
	
    /**
     * Finds the Articles model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Articles the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Meeting::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    //入场码
    public function actionPzcode()
    {
        $pingzheng= Yii::$app->request->get()["code"];
        return $this->render('pzcode',['code'=>$pingzheng]);
    }
    //会议报名第一步 填写信息 调取表单元素
    public function actionEnroll($id)
    { 

        $setinfo = Yii::$app->db->createCommand('SELECT * FROM activity where ac_id='.$id)->queryOne();
        if(!$setinfo['ac_id'])
        {
             header("Content-type: text/html; charset=utf-8");
             echo "<script>alert('此活动不存在');history.go(-1);history.go(-1);</script>";
             exit;
        }
        elseif($setinfo['ac_status']==0)
        {
             header("Content-type: text/html; charset=utf-8");
             echo "<script>alert('此活动未发布');history.go(-1);history.go(-1);</script>";
             exit;
        }
        elseif($setinfo['ac_display']==0)
        {
            header("Content-type: text/html; charset=utf-8");
            echo "<script>alert('此活动未进行');history.go(-1);history.go(-1);</script>";
            exit;
        }
        elseif($setinfo['ac_display']==40)
        {
            header("Content-type: text/html; charset=utf-8");
            echo "<script>alert('此活动已结束');history.go(-1);history.go(-1);</script>";
            exit;
        }
        else
        {
             //活动是否开启会员登录 1会员登录 0游客登录
        if($setinfo['me_status']==1)
        {
            if(!Yii::$app->user->id)
            {
                return $this->redirect(['/auth/login']);
            }
        }               
        //调用函数查找所有表单元素
        $custom_elements_wap = Utils::bdelements($setinfo['cu_id']);
        //如果是手机调到手机页面
        if(Utils::isMobile())
        {
            $layout = 'menroll';
            return $this->render('menroll',['custom_elements_wap'=>$custom_elements_wap,'id'=>$id,'setinfo'=>$setinfo]);
        }
        else
        {
            return $this->render('enroll',['custom_elements_wap'=>$custom_elements_wap,'id'=>$id,'setinfo'=>$setinfo]);
        }
        }
       
        
    }
    //添加会议报名信息到数据库
    public function actionAddcustom()
    {
         $setinfo = Yii::$app->db->createCommand('SELECT * FROM activity where ac_id='.Yii::$app->request->post()['ac_id'])->queryOne();
         if(Yii::$app->request->post())
        {
            $sub_info = Utils::eleadd(Yii::$app->request->post()['ac_id']);
            $addinfo = Yii::$app->db->createCommand()->insert('custom_info', [ 'add_time' => time(), 'sub_info' => $sub_info,'ac_id'=>Yii::$app->request->post()['ac_id']])->execute();
            $nextid = Yii::$app->db->getLastInsertID();
            if($addinfo > 0)
            {
                return $this->redirect(['/meetingenroll/confirm','id'=>$nextid,'ac_id'=>Yii::$app->request->post()['ac_id']]);
            }
            else
            {
                 Yii::$app->session->setFlash('success', Yii::t('app', '报名失败！！'));
            }
        }
    }
    //会议报名第二步 确认信息 $id为info—id,ac_id为活动id
    public function actionConfirm($id,$ac_id)
    {
        $setinfo = Yii::$app->db->createCommand('SELECT * FROM activity where ac_id='.$ac_id)->queryOne();
        $list = Utils::eleinfo($id);
        if(Utils::isMobile())
        {
            return $this->render('mconfirm',['list'=>$list,'setinfo'=>$setinfo,'bd_id'=>$id]);
        }
        else
        {
            return $this->render('confirm',['list'=>$list,'setinfo'=>$setinfo,'bd_id'=>$id]);
        }
        
    }
    //会议报名第三步 提交成功
    public function actionBmsuccess(){
        if(Yii::$app->request->post())
        {
            //$ac_id为活动id，bd——id为表单id
            $ac_id = Yii::$app->request->post()['ac_id'];
            $bd_id = Yii::$app->request->post()['bd_id'];
            $status = Yii::$app->request->post()['status'];
            $setinfo = Yii::$app->db->createCommand('SELECT * FROM activity where ac_id='.$ac_id)->queryOne();
            $list = Utils::eleinfo($bd_id);
            $upstatus = Yii::$app->db->createCommand('UPDATE custom_info SET status='.$status.' WHERE info_id='.$bd_id)->execute();
            $cusinfo = Yii::$app->db->createCommand('SELECT * FROM custom_info where info_id='.$bd_id)->queryOne();
            if($cusinfo['status']=='1')
            {
                //报名成功生成凭证码
                $pingzheng = rand(1000000,time());
                $pingzhengcode =  Yii::$app->request->hostInfo.'/code/zy/?code='.$pingzheng;
                QrCode::png($pingzhengcode,'upload/erm/'.$pingzheng.'.png', 'L', 20, 2); 
                Yii::$app->db->createCommand('UPDATE custom_info SET code='.$pingzheng.' WHERE info_id='.$bd_id)->execute();
                $subinfos = Yii::$app->db->createCommand("select sub_info from custom_info where info_id=".$bd_id)->queryAll();
                $subinfos =  unserialize($subinfos[0]['sub_info']);
                foreach ($subinfos as $key => $value) {
                   if($value['type']=="email")
                   {
                        $email = $value['value'];
                   }
                   if($value['name']=="姓名")
                   {
                        $name = $value['value'];
                   }
                   else
                   {
                        $name="匿名";
                   }
                }
                //报名成功发送邮件
                $mailer = SwfiEmail::getEmail();
                $mail= $mailer->compose();
                $mail->setTo($email);
                $mail->setSubject("恭喜！您已成功报名参加");
                $host = Yii::$app->request->hostInfo.'/code/zy/?code='.$pingzheng;
                $uname = $name;
                //$mail->setTextBody('Test conten1231123t');
                $content = '<p style="text-align: center;">
<span style="font-family: 微软雅黑, &#39;Microsoft YaHei&#39;; font-size: 18px;">恭喜！您已成功报名参加&nbsp;'.$setinfo['ac_name'].'</span><span style="font-family: 微软雅黑, &#39;Microsoft YaHei&#39;; font-size: 14px;"></span>
</p>
<hr/>
<p>
<span style="font-family: 微软雅黑, &#39;Microsoft YaHei&#39;; font-size: 14px;"></span>
</p>
<p>
<span style="font-family: 微软雅黑, &#39;Microsoft YaHei&#39;; font-size: 14px;"><br/></span>
</p>
<p>
<span style="font-family: 微软雅黑, &#39;Microsoft YaHei&#39;; font-size: 14px;">尊敬的'.$uname.'</span><br/>
</p>
<p>
<span style="font-family: 微软雅黑, &#39;Microsoft YaHei&#39;; font-size: 14px;"></span>
</p>
<p style="text-align: center;">
<span style="font-family: 微软雅黑, &#39;Microsoft YaHei&#39;; font-size: 14px;"><a href="'.$host.'">这是您本次的参会凭证</a></span>
</p>
<p>
<span style="font-family: 微软雅黑, &#39;Microsoft YaHei&#39;; font-size: 14px;">您本次的参会费用为</span>
</p>

<p style="text-align: right;">
<br/>
</p>
<hr/>
<p style="text-align: right;">
<span style="font-family: 微软雅黑, &#39;Microsoft YaHei&#39;; font-size: 14px;">&nbsp; &nbsp;| &nbsp;由协会管理系统的技术支持.&nbsp;</span><br/>
</p>';
            $mail->setHtmlBody($content);//发布可以带html标签的文本
            if($mail->send()){
                Yii::$app->session->setFlash('success', '邮件发送成功！');
            }else{
                Yii::$app->session->setFlash('error','邮件发送失败！');
            }
            //邮件发送完成
            }
        }
        $cusinfos = Yii::$app->db->createCommand("select info_id,code from custom_info where info_id=".$bd_id)->queryAll();
        //var_dump($cusinfo);die();
        if(Utils::isMobile())
        {
            return $this->render('mbmsuccess',['list'=>$list,'setinfo'=>$setinfo,'cusinfo'=>$cusinfos]);  
        }
        else
        {
            return $this->render('bmsuccess',['list'=>$list,'setinfo'=>$setinfo,'cusinfo'=>$cusinfos]);  
        }
        
    }


   
}
